package com.project.nimsen.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dao.IBaseDao;
import com.project.nimsen.dto.ColumnDto;
import com.project.nimsen.entity.Colfile;
import com.project.nimsen.entity.Coltype;
import com.project.nimsen.entity.Filearchivrelation;
import com.project.nimsen.entity.User;
import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.service.IFilearchivrelationService;
import com.project.nimsen.service.ISiteService;
import com.project.nimsen.util.NimsenUtil;
import com.project.nimsen.util.WebUtil;
import com.project.jdbc.dao.IBaseJdbcDao;
import com.project.jdbc.service.BaseServiceImpl;
import com.project.jdbc.utils.Finder;
import com.project.jdbc.utils.Page;
@Repository("coltypeService")
public class ColtypeServiceImpl extends BaseServiceImpl implements
		IColtypeService {
	@Resource
	WebUtil webUtil;
	@Resource
	IBaseDao baseDao;
	@Resource
	ISiteService siteService;
	@Resource
	IFilearchivrelationService relationService;
	protected IBaseJdbcDao getBaseDao() {
		return baseDao;
	}
	public String findNextNum(ColumnDto dto ) throws Exception {
//		Finder finder = new Finder("select count(id) from coltype where active!=1");
		String pnumber = dto.getPnumber();
		Finder finder = new Finder("select count(id) from coltype where siteid=:siteid");
		finder.setParam("siteid", dto.getSiteid());
		if(StringUtils.isNotBlank(pnumber)){
			finder.append(" and pnumber=:pnumber");
			finder.setParam("pnumber", pnumber);
		}else
			finder.append(" and (pnumber is null or pnumber='' or pnumber='0')");
		Map<String, Object> map = baseDao.queryForObject(finder);
		Integer count = Integer.parseInt(map.get("count(id)").toString());
		count++;
		if(StringUtils.isNotBlank(pnumber))
			return pnumber+"-"+count;
		else
			return count+"";
		/*if(count>999)
			return null;
		if(StringUtils.isNotBlank(pnumber))
			return pnumber+NimsenUtil.threeDigit(count);
		return NimsenUtil.threeDigit(count);*/
	}
	public Map<String, Object> findVilidate(ColumnDto dto) throws Exception {
		if(dto==null)
			return null;
		Finder finder = new Finder("select id from coltype where active!=1 and siteid=:siteid");
		finder.setParam("siteid", dto.getSiteid());
		finder.append(" and ").append(dto.getValifield()).append("=:filed");
		finder.setParam("filed", dto.getValivalue());
		if(StringUtils.isNotBlank(dto.getPnumber())){
			finder.append(" and pnumber=:pnumber");
			finder.setParam("pnumber", dto.getPnumber());
		}else
			finder.append(" and (pnumber is null or pnumber='' or pnumber='0')");
		//如果id存在表示为修改
		if(StringUtils.isNotBlank(dto.getId())){
			finder.append(" and id!=:id");
			finder.setParam("id", dto.getId());
		}
		return baseDao.queryForObject(finder);
	}
	public List<Map<String, Object>> finder(ColumnDto dto) throws Exception {
		Finder finder = new Finder("select c.id as entityid,c.number,c.pnumber,c.colname,c.sort,"
			+ "c.vurl,c.showstatus,u.username as createUserName,c.createTime,c.listmodel,c.archivesmodel"
			+ ",c.phonelistmodel,c.phonearchmodel,c.padlistmodel,c.padarchmodel,"
			+ "c.createUser from coltype as c left join user as u on "
			+ "c.createUser=u.id where c.active!=1 and u.active!=1");
		if(dto==null){
			finder.append(" order by c.sort asc");
			return baseDao.queryForList(finder);
		}
		if(StringUtils.isNotBlank(dto.getSiteid())){
			finder.append(" and c.siteid=:siteid");
			finder.setParam("siteid", dto.getSiteid());
		}
		finder.append(" order by c.sort asc");
		return baseDao.queryForList(finder);
	}
	public Map<String, Object> findEntity(ColumnDto dto) throws Exception {
		if(dto==null)
			return null;
		Finder finder = new Finder("select id,number,pnumber,colname,showstatus,"
			+ "sort,vurl,listmodel,archivesmodel,phonelistmodel,phonearchmodel,"
			+ "padlistmodel,padarchmodel,createUser,createTime,active "
			+ "from coltype where id=:id");
		finder.setParam("id", dto.getId());
		return baseDao.queryForObject(finder);
	}
	public Coltype findEntityById(String id) throws Exception {
		if(StringUtils.isBlank(id))
			return null;
		Finder finder = new Finder("select * from coltype where active!=1 and id=:id");
		finder.setParam("id", id);
		return baseDao.queryForObject(finder, Coltype.class);
	}
	public List<Map<String, Object>> findChild(ColumnDto dto) throws Exception {
		if(StringUtils.isBlank(dto.getNumber())&&StringUtils.isNotBlank(dto.getId())){
			Coltype col = findEntityById(dto.getId());
			dto.setNumber(col.getNumber());
		}
		Finder finder = new Finder("select id,number,pnumber,colname,showstatus,sort,vurl"
			+ ",listmodel,archivesmodel,phonelistmodel,phonearchmodel,padlistmodel,"
			+ "padarchmodel,createUser,createTime,active from coltype where"
			+ " active!=1 and siteid=:siteid");
		finder.setParam("siteid", dto.getSiteid());
		if(StringUtils.isNotBlank(dto.getNumber())){
			finder.append(" and number!=:number");
			finder.setParam("number", dto.getNumber());
		}
		if(dto.getAllchild()){
			finder.append(" and number like :lnumber");
			finder.setParam("lnumber", dto.getNumber()+"%");
		}else{
			finder.append(" and pnumber=:pnumber");
			finder.setParam("pnumber",dto.getNumber());
		}
		return baseDao.queryForList(finder);
	}
	public boolean deleteByDto(ColumnDto dto) throws Exception {
		Finder finder = new Finder("update coltype set active=1 where active!=1");
		if(StringUtils.isNotBlank(dto.getId())){
			finder.append(" and id=:id");
			finder.setParam("id", dto.getId());
		}
		return baseDao.update(finder)>0;
	}
	public Coltype findEntityByNumer(String number, String siteid) throws Exception {
		if(StringUtils.isBlank(number))
			return null;
		Finder finder = new Finder("select * from coltype where active!=1 and number=:number and siteid=:siteid");
		finder.setParam("number", number);
		if(StringUtils.isNotBlank(siteid))
			finder.setParam("siteid", siteid);
		else
			finder.setParam("siteid", currentSiteId());
		return baseDao.queryForObject(finder, Coltype.class);
	}
	public List<Map<String, Object>> findByArchInfo(ColumnDto dto)
			throws Exception {
		Finder finder = new Finder("select col.id,col.number,col.pnumber,col.colname,"
			+ "col.showstatus,col.sort,col.vurl,col.listmodel,col.archivesmodel,col.phonelistmodel,col.phonearchmodel"
			+ ",col.padlistmodel,col.padarchmodel,col.createUser,"
			+ "col.createTime,col.active,arc.mancol from coltype as col left join archivescolumn"
			+ " as arc on col.id=arc.coltypeid where col.active!=1 and arc.active!=1 and col.siteid=:siteid");
		finder.setParam("siteid", currentSiteId());
		if(StringUtils.isNotBlank(dto.getArchid())){
			finder.append(" and arc.archives=:archives");
			finder.setParam("archives", dto.getArchid());
		}
		return baseDao.queryForList(finder);
	}
	public Coltype findEntityByVurl(String vurl, String siteid) throws Exception {
		if(StringUtils.isBlank(vurl))
			return null;
		Finder finder = new Finder("select * from coltype where active!=1 and vurl=:vurl and siteid=:siteid");
		if(StringUtils.isBlank(siteid))
			finder.setParam("siteid", currentSiteId());
		else
			finder.setParam("siteid", siteid);
		finder.setParam("vurl", vurl);
		return baseDao.queryForObject(finder, Coltype.class);
	}
	public List<Map<String, Object>> findTagByDto(ColumnDto dto)
			throws Exception {
		Page page = null;
		if(dto.getNum()>0)
			page = new Page(1, dto.getNum());
		Finder finder = new Finder("select id,number,pnumber,colname,showstatus,sort,vurl"
				+ ",listmodel,archivesmodel,phonelistmodel,phonearchmodel,padlistmodel,"
				+ "padarchmodel,createUser,createTime,active from coltype where"
				+ " active!=1 and showstatus='show' and siteid=:siteid");
		if(StringUtils.isBlank(dto.getSiteid()))
			finder.setParam("siteid", currentSiteId());
		else
			finder.setParam("siteid", dto.getSiteid());
		//与父级的同一级别时和顶级栏目时的处理
		if("PARENT".equals(dto.getNumber())||"TOPARENT".equals(dto.getNumber())){
			//父级别为顶级，与顶级栏目
			if(dto.getPnumber()==null){
				finder.append(" and pnumber is null");
			}else{
				//父级别信息
				Coltype pcol = findEntityByNumer(dto.getPnumber(), null);
				//如果父级别是顶级栏目
				if(pcol.getPnumber()==null){
					finder.append(" and pnumber is null");
				}else{
					finder.append(" and pnumber =:pnumber");
					finder.setParam("pnumber", pcol.getPnumber());
				}
			}
		//与当前栏目同一级别
		}else if("OWNER".equals(dto.getNumber())){
			//如果当前栏目是顶级栏目
			if(dto.getPnumber()==null){
				finder.append(" and pnumber is null");
			}else{
				finder.append(" and pnumber =:pnumber");
				finder.setParam("pnumber", dto.getPnumber());
			}
		//当前栏目的子栏目
		}else if("CHILD".equals(dto.getNumber())){
			finder.append(" and pnumber =:pnumber");
			finder.setParam("pnumber", dto.getCurrnumber());
		}else{
			//指定栏目的子栏目
			finder.append(" and pnumber =:pnumber");
			finder.setParam("pnumber", dto.getNumber());
		}
		if("desc".equals(dto.getOrderType()))
			finder.append(" order by sort desc");
		else
			finder.append(" order by sort asc");
		
		return baseDao.queryForList(finder, page);
	}
	public List<Map<String, Object>> findAllParentByfPnum(String pnumber, String siteid)
			throws Exception {
		//用于存储所有父级别的信息
		List<String> pnumbers = new ArrayList<String>();
		pnumbers.add(pnumber);
		addPnumber(pnumbers, pnumber);
		Finder finder = new Finder("select id,number,pnumber,colname,showstatus,sort,vurl"
			+ ",listmodel,archivesmodel,phonelistmodel,phonearchmodel,padlistmodel,padarchmodel,"
			+ "createUser,createTime,active from coltype where"
			+ " active!=1 and showstatus='show' and number in (:numbers) and siteid=:siteid");
		if(StringUtils.isNotBlank(siteid))
			finder.setParam("siteid", siteid);
		else
			finder.setParam("siteid", currentSiteId());
		finder.setParam("numbers", pnumbers);
		return baseDao.queryForList(finder);
	}
	private void addPnumber(List<String> list, String number){
		if(number.length()<4)
			return;
		String pnumber = number.substring(0, number.length()-1);
		list.add(pnumber);
		if(pnumber.length()>3)
			addPnumber(list, pnumber);
	}
	private String currentSiteId() throws Exception{
		User use = webUtil.getCurrUser();
		Map<String, Object> site = siteService.findByManagerId(use.getId());
		String siteid = site.get("id").toString();
		return siteid;
	}
	public boolean save(ColumnDto dto) throws Exception {
		Coltype col = dto.getColtype();
		if(col==null)
			return false;
		String col_id = null;
		if(StringUtils.isBlank(col.getId())){
			Object obj_id = baseDao.saveEntity(col);
			col_id = NimsenUtil.obj2String(obj_id);
		}else{
			baseDao.update(col);
			col_id = col.getId();
		}
		//保存信息
		Filearchivrelation rela = relationService.findByValue(NimsenConstant.FILE_RELATION_MICROIMG);
		Finder imgupdate = new Finder("update colfile set active=1 where coltypeid=:coltypeid and active!=1"
				+ " and relationid=:relationid");
		imgupdate.setParam("relationid", rela.getId());
		imgupdate.setParam("coltypeid", col_id);
		baseDao.update(imgupdate);
		//把副栏目添加到list里
		String microimgid = dto.getMicroimgid();
		if(StringUtils.isBlank(microimgid))
			return true;
		
		//添加缩略图
		Colfile arfile = new Colfile();
		arfile.setActive(0);
		arfile.setColtypeid(col_id);
		arfile.setCreateTime(new Date());
		arfile.setCreateUser(dto.getCurruseid());
		arfile.setDescs("栏目的缩略图");
		arfile.setFileid(microimgid);
		arfile.setRelationid(rela.getId());
		baseDao.saveEntity(arfile);
		return true;
	}
}
